<template>
  <CardSmall title="温度" :height="height">
    <div ref="chartRef" class="chart"></div>
  </CardSmall>
</template>
<script setup>
  import * as echarts from 'echarts';
  import { echartTheme } from './echartTheme.js';
  import CardSmall from '@/components/CardSmall.vue';
  import dayjs from 'dayjs';
  import request from '@/utils/request.js';

  // 阈值
  const { Temperature } = window.thresholdData;

  const props = defineProps({
    height: {
      type: [Number, String],
      default: 300,
    },
    data: {
      type: Array,
      default: () => [],
    },
  });
  watch(
    () => props.data,
    (newVal) => {
      renderChart(newVal);
    }
  );

  const chartInstance = shallowRef(null);
  const chartRef = useTemplateRef('chartRef');

  const initChart = () => {
    chartInstance.value = echarts.init(chartRef.value, echartTheme);
    // ...绑定事件等
  };
  const renderChart = (wsContent = []) => {
    if (wsContent.length === 0) {
      return;
    }
    const { seriesData } = formatData(wsContent);
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'line',
        },
        renderMode: 'html',
        appendTo: document.body,
      },
      legend: {
        show: true,
      },
      grid: {
        top: 64,
      },
      xAxis: {
        type: 'time',
      },
      yAxis: {
        type: 'value',
        name: '温度(°C)',
        min: 'dataMin',
      },
      series: [...seriesData],
    };
    chartInstance.value.setOption(option);
  };

  onMounted(() => {
    initChart();
    window.addEventListener('resize', resize);
    getData().then((res) => {
      renderChart(JSON.parse(res.content));
    });
  });
  onUnmounted(() => {
    chartInstance.value?.dispose();
    window.removeEventListener('resize', resize);
  });
  const resize = () => {
    chartInstance.value?.resize();
  };

  const formatData = (_content = []) => {
    // 排序
    const content = [..._content];
    content.sort((a, b) => {
      return dayjs(a.dateTime).isAfter(dayjs(b.dateTime)) ? 1 : -1;
    });

    const lineOps = {
      type: 'line',
      showSymbol: false,
    };
    const seriesDataMap = {};
    content.slice(-20).forEach((c) => {
      const { dateTime, items } = c;
      items.forEach((item) => {
        if (!seriesDataMap['温度' + item.num]) {
          seriesDataMap['温度' + item.num] = { data: [] };
        }
        seriesDataMap['温度' + item.num].data.push([
          dateTime,
          item.temperature,
        ]);
      });
    });

    const seriesData = [];
    for (const key in seriesDataMap) {
      if (Object.prototype.hasOwnProperty.call(seriesDataMap, key)) {
        seriesData.push({
          name: key,
          ...lineOps,
          data: seriesDataMap[key].data,
        });
      }
    }

    const markLine = {
      data: [
        {
          name: '阈值',
          yAxis: Temperature,
        },
      ],
      silent: true,
      lineStyle: {
        color: '#fe1a1a',
        type: 'solid',
      },
      symbol: ['rect', 'none'],
      symbolOffset: [
        ['-50%', '50%'],
        [0, 0],
      ],
      label: {
        // show: false,
        color: '#fe1a1a',
        // position:'insideEndTop',
        formatter: (param) => {
          const { name } = param;
          return name;
        },
      },
    };

    seriesData[0].markLine = markLine;

    seriesData.forEach((s) => {
      const pointData = [];
      const markPoint = {
        data: pointData,
        symbolSize: 24,
        label: { fontSize: 8, color: '#b5dbff' },
      };
      s.data.forEach((sItem) => {
        const [dateTime, value] = sItem;
        if (value > Temperature) {
          pointData.push({ coord: [dateTime, value], value });
        }
      });
      s.markPoint = markPoint;
    });

    return { seriesData };
  };
  const getData = () => {
    return request({
      method: 'post',
      url: '/DataScreen/database/lulan',
      data: {
        'method': 'getThermalTemperature',
        'format': 'JSON',
        'content': `{\"id\":1,\"startTime\":null,\"endTime\":null}`,
      },
    });
  };
</script>
<style lang="scss" scoped>
  .chart {
    height: 100%;
  }
</style>
